package com.neusoft.tmall.security;

import cn.hutool.core.util.URLUtil;
import com.google.api.client.util.Lists;
import com.neusoft.tmall.ums.service.UmsResourceService;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 只是将数据中的资源封装到SecurityMetadataSource,以方便投票器进行权限比较
 * @Author: duan
 * @Date: Create in 20:49 2020/7/26
 */
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    private UmsResourceService umsResourceService;

    public DynamicSecurityMetadataSource(UmsResourceService umsResourceService) {
        this.umsResourceService = umsResourceService;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        List<ConfigAttribute> list = Lists.newArrayList();
        if (umsResourceService == null) {
            return list;
        }
        Map<String, ConfigAttribute> map = umsResourceService.loadAuthResources();
        //获取当前访问的路径
        String url = ((FilterInvocation) object).getRequestUrl();
        String path = URLUtil.getPath(url);
        PathMatcher pathMatcher = new AntPathMatcher();
        Iterator<String> iterator = map.keySet().iterator();
        //获取访问该路径所需资源
        while (iterator.hasNext()) {
            String pattern = iterator.next();
            if (pathMatcher.match(pattern, path)) {
                list.add(map.get(pattern));
            }
        }
        return list;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}

